import axios from 'axios'
import { Message, MessageBox, Notification, Loading } from 'element-ui'
import store from '@/store'
import router from '../router'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: '', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests，允许后台的cookie传递到前端
  timeout: 100000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['want-token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    store.dispatch('app/setLoading', false);
    return response
  },
  error => {
    //报错先关闭Loading
    store.dispatch('app/setLoading', false);
    switch (error.response.status) {
      case 400:
        Notification.error({
          title: "温馨提示：",
          message: error.response.data
        });
        break
      case 401:
        MessageBox.confirm('token已过期，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        break
      case 402:
        Notification.error({
          title: "温馨提示：",
          message: error.response.data
        });
        break
      case 404:
        router.replace("/404");
        break
      case 405:
        Message({
          message: 'http请求方式有误！',
          type: 'error',
          duration: 1500,
        })
        break
      case 500:
        router.replace("/500");
        break
      case 501:
        Notification.error({
          title: "温馨提示：",
          message: '服务器不支持当前请求所需要的某个功能！'
        });
        break
      default: {
        router.replace("/500");
        break
      }
    }
    return Promise.reject(error)
  }
)

export default service
